<?php

namespace addons\qingdong\model;

use addons\qingdong\library\Wechat;
use addons\qingdong\library\WechatEnterprise;
use fast\Http;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *提醒消息
 */
class Message extends Model
{
    use SoftDelete;

    // 表名,不含前缀
    const   EXAMINE_TYPE = 'examine';//审批
    const   CONSUME_TYPE = 'consume';//费用
    const   RECORD_TYPE = 'record';//
    const   COMMENT_TYPE = 'comment';//评论
    const   CONTRACT_TYPE = 'contract';//合同
    const   PLAN_TYPE = 'plan';//回款计划
    const   RECEIVABLES_TYPE = 'receivables';//回款
    const   CUSTOMER_TYPE = 'customer';//客户
    const   SIGN_TYPE = 'sign';//签到
    const   DAILY_TYPE = 'daily';//报告
    const   ACHIEVEMENT_TYPE = 'achievement';//业绩
    const EXAMINE_ADOPT_TYPE = 'examine_adopt';//审核通过
    const EXAMINE_REFUSE_TYPE = 'examine_refuse';//审批通过
    const CONTRACT_EXPIRE_TYPE = 'contract_expire';//合同到期
    const PLAN_EXPIRE_TYPE = 'plan_expire';//计划到期
    const SEAS_TYPE = 'seas';//公海
    const   EVENT_TYPE       = 'event';//日程
    const   NOTICE_TYPE = 'notice';//公告
    const   WORKORDER_TYPE = 'workorder';//工单
    const   APPROVAL_TYPE = 'approval';//
    const   BUSINESS_TYPE = 'business';//商机
    const   CARD_TYPE = 'card';//补卡
    const   LEAVE_TYPE = 'leave';//请假


    protected $name = 'qingdong_message';//
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    public static function setRead($relation_type, $relation_id = 0, $to_staff_id = 0)
    {
        $where = [
            'relation_type' => $relation_type,
            'status' => 0
        ];
        if (!empty($relation_id)) {
            $where['relation_id'] = $relation_id;
        }
        if (!empty($to_staff_id)) {
            $where['to_staff_id'] = $to_staff_id;
        }
        return Message::where($where)->update(['read_time' => time(), 'status' => 1]);
    }


    //发送人

    /**
     * 添加通知消息
     * @param $relation_type string 类型
     * @param $relation_id int 类型id
     * @param $to_staff_id int 接收人
     * @param $from_staff_id int 发送人
     * @return bool
     * @throws Exception
     */
    public static function addMessage($relation_type, $relation_id, $to_staff_id, $from_staff_id)
    {

        $addMessage = [
            'to_staff_id' => $to_staff_id,
            'from_staff_id' => $from_staff_id,
            'send_time' => time(),
            'status' => 0,
        ];
        $contents = '';
        switch ($relation_type) {//不同类型打开不同页面
            case self::EXAMINE_ADOPT_TYPE:
                $examine = ExamineRecord::get($relation_id);
                $addMessage['relation_type'] = $examine['relation_type'];
                $addMessage['relation_id'] = $examine['relation_id'];
                break;
            case self::EXAMINE_REFUSE_TYPE:
                $examine = ExamineRecord::get($relation_id);
                $addMessage['relation_type'] = $examine['relation_type'];
                $addMessage['relation_id'] = $examine['relation_id'];
                break;
            case self::COMMENT_TYPE:
                $addMessage['relation_type'] = Message::RECORD_TYPE;
                $addMessage['relation_id'] = $relation_id;
                break;
            case self::CONTRACT_EXPIRE_TYPE:
                $addMessage['relation_type'] = Message::CONTRACT_TYPE;
                $addMessage['relation_id'] = $relation_id;
                break;
            case self::PLAN_EXPIRE_TYPE:
                $addMessage['relation_type'] = Message::PLAN_TYPE;
                $addMessage['relation_id'] = $relation_id;
                break;
            case self::APPROVAL_TYPE:
                $addMessage['relation_type'] = Message::APPROVAL_TYPE;
                $addMessage['relation_id'] = $relation_id;
                $contents ='您有新的办公申请提醒';
                break;
            case self::CUSTOMER_TYPE:
                $addMessage['relation_type'] = Message::CUSTOMER_TYPE;
                $addMessage['relation_id'] = $relation_id;
                $contents =Customer::where(array('id'=>$relation_id))->value('name');
                break;
            case self::BUSINESS_TYPE:
                $addMessage['relation_type'] = Message::BUSINESS_TYPE;
                $addMessage['relation_id'] = $relation_id;
                $contents =Business::where(array('id'=>$relation_id))->value('name');
                break;
            default:
                $addMessage['relation_type'] = $relation_type;
                $addMessage['relation_id'] = $relation_id;
        }

        $data = NoticeTemplate::getTypeForData($relation_type);
        $data=NoticeTemplate::replaceTemplateContent($data,$relation_type,$relation_id,$from_staff_id);
        $addMessage['content'] = $data['first'] ?? $contents;
        $Model = new self;
        $result = $Model->save($addMessage);
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($Model->getError());
        }

        $fromStaff = Staff::get($to_staff_id);

        $corpid = AdminConfig::getConfigValue('corpid', 'wechat');
        $corpsecret = AdminConfig::getConfigValue('corpsecret', 'wechat');
        //企业微信通知
        if($corpid && $corpsecret){

            $enterpriseData = NoticeTemplate::getTypeForEnterpriseData($relation_type);

            if($enterpriseData){
                $enterpriseData=NoticeTemplate::replaceTemplateContent($enterpriseData,$relation_type,$relation_id,$to_staff_id);
                $enterpriseMessageData = [
                    'title' =>  $enterpriseData['first'],
                    'description' =>  $enterpriseData['remark'],
                    'content_item'=>[]
                ];
                for ($i = 1; $i <= 5; $i++) {
                    if ($enterpriseData['keyword' . $i]) {
                        $enterpriseMessageData['content_item'][] = [
                            'key' => $enterpriseData['keyword' . $i . '_title'],
                            'value' => $enterpriseData['keyword' . $i],
                        ];
                    }
                }
                $wechatEnterprise= new WechatEnterprise();
                $touser=$fromStaff['touser'];

                if(empty($touser)){
                    $touser=$wechatEnterprise->userid($fromStaff['mobile']);
                }
                if($touser){
                    $result=$wechatEnterprise->sendTemplate($touser,$enterpriseMessageData);
                }
            }
        }
        $templateId = $data['template_id'] ?? '';
        //微信小程序通知
        if ($templateId) {
            $messageData = [
                'first' => [
                    'value' => $data['first'],
                ],
            ];
            for ($i = 1; $i <= 5; $i++) {
                if ($data['keyword' . $i]) {
                    $messageData['keyword' . $i] = [
                        'value' => $data['keyword' . $i],
                        'color' => $data['keyword' . $i . '_color']
                    ];
                }
            }
            if ($data['remark']) {
                $messageData['remark'] = [
                    'value' => $data['remark'],
                    'color' => $data['remark' . '_color']
                ];
            }

            $result=self::sendWechat($fromStaff['openid'] ?? $fromStaff['wx_openid'], $templateId, $messageData, 'pages/news/theReminder/theReminder');
        }
        return true;
    }


    /**
     * 提交给微信
     * @param $openid
     * @param $templateId
     * @param $data
     * @param $pagepath
     * @return bool
     */
    public static function sendWechat($openid, $templateId, $data, $pagepath)
    {
        if (empty($openid)) {
            return false;
        }
        $miniAppid = AdminConfig::getConfigValue('mini_appid', 'wechat');
        $app_id = AdminConfig::getConfigValue('appid', 'wechat');
        $web_url = AdminConfig::getConfigValue('web_url', 'wechat');

        if (!empty($miniAppid)) {//打开小程序页面
            $mini_wechat = new Wechat('wxMiniProgram');
            $token = $mini_wechat->getAccessToken();
            $params = [
                'touser' => $openid,
                'mp_template_msg' => [
                    'appid' => $app_id,//
                    'template_id' => $templateId,//模板ID
                    'url' => $web_url . $pagepath,//
                    'data' => $data,
                    'miniprogram' => [
                        'appid' => $mini_wechat->config['app_id'],
                        'pagepath' => $pagepath,
                    ],
                ]
            ];
            $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=' . $token['access_token'];
        } else {
            $mini_wechat = new Wechat('wxOfficialAccount');
            $token = $mini_wechat->getAccessToken();
            $params = [
                'touser' => $openid,
                'template_id' => $templateId,
                'url' => $web_url . $pagepath,
                'data' => $data
            ];
            $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token['access_token'];

        }
        $json = json_encode($params, JSON_UNESCAPED_UNICODE);
        $result = Http::post($url, $json);
        $arr_result = json_decode($result, true);
        //添加日志
        PushReload::create([
            'openid' => $openid,
            'template_id' => $templateId,
            'data' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'pagepath' => $pagepath,
            'errcode' => $arr_result['errcode'],
            'result' => $result
        ]);
        if ($arr_result['errcode'] === 0) {
            return true;
        }

        return false;
    }


    public function getSendTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function fromStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'from_staff_id')->field('id,name');
    }

    public function examine()
    {
        return $this->hasOne(ExamineRecord::class, 'id', 'relation_id')->field('id,relation_type,relation_id');
    }
}
